package com.hq.shop12auth.controller;

import com.hq.commons.constatns.AuthConstatns;
import com.hq.commons.ov.Customer;
import com.hq.shop12auth.feign.api.UserService;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthBaiduRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/oauth")
public class RestAuthController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void renderAuth(HttpServletResponse response) throws IOException {
//        获取应用的信息
        AuthRequest authRequest = getAuthRequest();
//        引导到百度登录
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public void login(AuthCallback callback, HttpSession session,HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
//        根据code获取AccessToken
        AuthResponse login = authRequest.login(callback);
//        判断是否授权成功
        if (login.ok()) {
            AuthUser authUser = (AuthUser) login.getData();
//            考虑用户是否第一次使用第三方登录
            String uuid = authUser.getUuid();
            Customer customer = userService.getUserById(uuid);
            if (customer == null) {
                customer = new Customer();
                customer.setUsername(authUser.getUsername());
                customer.setAuthId(uuid);
                userService.addUser(customer);
            }
//            把登录的用户放入到session中
            session.setAttribute(AuthConstatns.AUTH_SESSION, customer);
//            return "认证成功" + authUser;
            response.sendRedirect("http://localhost:81/home");
        } else {
//            return "认证授权失败";
            response.sendRedirect("http://localhost:81/auth/user/login");
        }
    }

    private AuthRequest getAuthRequest() {
        return new AuthBaiduRequest(AuthConfig.builder()
                .clientId("3VN7ZmfNH99cQHQyyyh9jcq3")
                .clientSecret("62IoavzFW0tYNYGgpqRvbkubrr82qzwf")
                .redirectUri("http://localhost:81/auth/oauth/callback")
                .build());
    }
}
